package com.tianji.remark.task;

import cn.hutool.core.util.StrUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.remark.constants.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 处理zset数据同步到mysql点赞数量
 *
 * @Author wangxinyi
 * @Date 2025/1/3 21:03
 */
@Component
@Slf4j
public class LikedTimesCheckTask {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitMqHelper mqHelper;

    private static final List<String> bizTypeList = Arrays.asList("QA", "NOTE");
    private static final int MAX_BIZ_SIZE = 30;//每次读取30个数据，避免这次还没处理完，下次定时任务又来了

    @Scheduled(fixedDelay = 30000L)
    public void checkLikedTimes() {
        ArrayList<LikedTimesDTO> likedTimesDTOList = new ArrayList<>();
        //1.读取并移除redis缓存中的点赞总数
        for (String bizType : bizTypeList) {
            String key = RedisConstants.LIKED_TIMES + bizType;
            Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMax(key, MAX_BIZ_SIZE);
            if (CollUtils.isEmpty(typedTuples)) {
                continue; //结束当前循环
            }
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                String value = typedTuple.getValue();
                Double score = typedTuple.getScore();
                if (value == null || score == null) {
                    continue;
                }
                LikedTimesDTO likedTimesDTO = new LikedTimesDTO();
                likedTimesDTO.setBizId(Long.valueOf(value));
                likedTimesDTO.setLikedTimes(score.intValue());
                likedTimesDTOList.add(likedTimesDTO);
            }
            //发送Mq消息
            if (CollUtils.isNotEmpty(likedTimesDTOList)) {
                String exchange = MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
                key = StrUtil.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);
                log.info("消息发送成功，消息为{}", likedTimesDTOList);
                mqHelper.send(exchange, key, likedTimesDTOList);
            }
        }
    }
}
